﻿-- Function: change_project_currency()

-- DROP FUNCTION change_project_currency();

CREATE OR REPLACE FUNCTION change_project_currency()
	RETURNS trigger AS
	$BODY$
	DECLARE                      
		changed boolean;                    
	BEGIN
			changed := new.default_curr is TRUE;
			IF changed and new.contract_id>0 THEN                         
				update project_currency 
				set 
					default_curr=False 
				where id in (Select id from project_currency where contract_id in (select distinct contract_id from project_currency where id=new.id)) and id!=new.id;
			END IF;
			IF changed and new.project_id>0 THEN                         
				update project_currency 
				set 
					default_curr=False 
				where id in (Select id from project_currency where project_id in (select distinct project_id from project_currency where id=new.id)) and id!=new.id;
			END IF;
			RETURN new;
	END;$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION change_project_currency() OWNER TO openerp;


DROP TRIGGER change_default_currency ON project_currency;

CREATE TRIGGER change_default_currency
  AFTER INSERT OR UPDATE
  ON project_currency
  FOR EACH ROW
  EXECUTE PROCEDURE change_project_currency();
